package org.jeecg.zhenxuan.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.zhenxuan.CommonUtils.CommonUtils;
import org.jeecg.zhenxuan.CommonUtils.SignatureUtil;
import org.jeecg.zhenxuan.Entity.PointFlow;
import org.jeecg.zhenxuan.Entity.UsersPoint;
import org.jeecg.zhenxuan.Repository.PointFlowRepository;
import org.jeecg.zhenxuan.Repository.UserRepository;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.transaction.Transactional;
import java.util.Date;

@Slf4j
@Controller
public class ReducePointController {
    @Autowired
    UserRepository userRepository;
    @Autowired
    PointFlowRepository pointFlowRepository;

    /**
     * 2019年8月12日
     * 根据openid减豆子
     * @param userNo
     * @param point
     * @return
     */
    @ResponseBody
    @RequestMapping("/reducePoint")
    @Transactional
    public JSONObject reducePointByOpenId(String userNo, String boNo, Integer point, String ts, String sign){
        JSONObject result = new JSONObject();

        //非空判断
        if (StringUtils.isBlank(userNo) || StringUtils.isBlank(ts) || StringUtils.isBlank(sign) ||  StringUtils.isBlank(boNo) || point==null) {
            result.put("status", 1);
            result.put("message", "参数为空！");
            return result;
        }
        //生成签名
        JSONObject json = new JSONObject();
        json.put("userNo",userNo);
        json.put("boNo",boNo);
        json.put("point",point);
        json.put("ts",ts);
        //md5key
        String md5Key = "xuanzhen";
        String mySign = SignatureUtil.makeSignature(json,md5Key);
        System.out.println(mySign);
        //检验签名
        if(!mySign.equals(sign)){
            result.put("status", 1);
            result.put("message", "签名错误");
            return result;
        }
        try {
            if(point < 0|| point>=2147483647) {
                result.put("status", 1);
                result.put("message", "商品数据出现错误，请稍后再试");
                return result;
            }
            PointFlow pointFlowTest = new PointFlow();
            pointFlowTest.setOpenId(userNo);
            pointFlowTest.setOperation("reduce");
            pointFlowTest.setOperationTime(new Date());
            pointFlowTest.setCount(point);
            pointFlowRepository.save(pointFlowTest);
            UsersPoint usersPoint = userRepository.getUserTestByOpenId(userNo);
            if(usersPoint==null){
                result.put("status", 1);
                result.put("message", "查询数据失败");
                return result;
            }
            if((usersPoint.getPointTotal()-point)<0){
                result.put("status", 1);
                result.put("message", "豆子数量不够");
                return result;
            }
            System.out.println(usersPoint.getPointTotal()-point);
            int Total = userRepository.updatePointTotal(usersPoint.getPointTotal()-point,userNo);
            System.out.println(Total);
            if(Total==0){
                result.put("status", 1);
                result.put("message", "扣减豆子失败");
            }
            usersPoint.setPointTotal(usersPoint.getPointTotal()-point);
            userRepository.save(usersPoint);
            result.put("point",usersPoint.getPointTotal());
            result.put("status",0);
            result.put("message","豆子已经减掉了");
            result.put("sn", "" + CommonUtils.randomSixDigital());
            return result;

        }catch (Exception e){
            log.error(e.getLocalizedMessage());
            e.printStackTrace();
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("status", 2);
            result.put("message", "没有查到数据");
        }
        return result;
    }

    /**
     * 2019年8月12日
     * 撤销根据openid减豆子
     * @param openId
     * @param Id
     * @return
     */
    @ResponseBody
    @RequestMapping("/undoreducePoint")
    @Transactional
    public JSONObject undoreducePointByOpenId(String openId, Integer Id){
        JSONObject result = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        JSONArray array = new JSONArray();
        if(Id==null){
            Id = pointFlowRepository.getMax(openId);
        }
        if(openId==null){
            result.put("status", 1);
            result.put("message", "参数为空！");
            return result;
        }
        try {
            UsersPoint usersPoint = userRepository.getUserTestByOpenId(openId);

            PointFlow pointFlowTest = pointFlowRepository.getPointFlowById(Id);
            usersPoint.setPointTotal(usersPoint.getPointTotal()+pointFlowTest.getCount());
            userRepository.save(usersPoint);
            jsonObject.put("point",pointFlowTest.getCount());
            jsonObject.put("status",0);
            jsonObject.put("message","豆子还回来了");
            array.add(jsonObject);
            pointFlowRepository.deleteById(Id);

            result.put("200",array);
        }catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("status", 2);
            result.put("message", "查询数据异常");
        }
        return result;
    }

    /**
     * 根据用户openId查询积分数
     * modify by 2019年11月26日 星期二
     * @param openid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserName")
    public JSONObject getUserName(String openid , @RequestParam(defaultValue = "default")String channel) {
        JSONObject result = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        if (openid == null || openid.equals("")) {
            result.put("status", 1);
            result.put("message", "参数为空！");
            return result;
        }

        log.info("查询的渠道为："+channel);

        try {
//            UsersPoint usersPoint = userRepository.getUserTestByOpenId(openid);
            UsersPoint usersPoint = userRepository.findUsersPointByOpenIdAndChannel(openid , channel);
            if(usersPoint==null){


                UsersPoint usersPointTemp = new UsersPoint();
                usersPointTemp.setLastModifyTime(new Date());
                usersPointTemp.setCreateTime(new Date());
                usersPointTemp.setOpenId(openid);
                usersPointTemp.setChannel(channel);
                usersPointTemp.setPointTotal(0);


                userRepository.save(usersPointTemp);


                result.put("status", 0);
                /**
                 * update by lsz 2019年11月20日
                 * 修复用户不存在，空指针异常
                 */
                result.put("message", "没有此用户，但是在用户积分表里加了一条记录！");
                result.put("Total",0);
                result.put("Name", "");

                return result;
            }
            jsonObject.put("Name", usersPoint.getName());
            jsonObject.put("PointTotal", usersPoint.getPointTotal());
            jsonObject.put("status", 0);
            result.put("Name",jsonObject.get("Name"));
            result.put("Total",jsonObject.get("PointTotal"));


            result.put("status", 0);

            /**
             * add by 2019年12月16日 星期一
             */
            result.put("data", usersPoint);

        }catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("status", 2);
            result.put("message", "查询数据异常");
        }
        log.info(result.toJSONString());
        return result;
    }


}
